<template>
  <Pages :current="0">
    <view class="page-header">
      <text class="header-title" @click="onSys">内容管理</text>
      <view class="header-actions">
        <picker mode="selector" :range="contentStore.contentTypes" :value="selectedTypeIndex" @change="handleTypeChange"
          class="type-picker">
          <view class="picker-wrapper">
            <text class="picker-text">{{ contentStore.contentTypes[selectedTypeIndex] }}</text>
          </view>
        </picker>
      </view>
    </view>

    <!-- 内容列表 -->
    <!-- 修改 scroll-view -->
    <scroll-view class="content-list-container" scroll-y :style="{ height: scrollHeight + 'px' }"
      @scrolltolower="handleLoadMore" @refresherrefresh="handleRefresh" refresher-enabled
      :refresher-triggered="refreshing">


      <view v-if="contentList.length === 0" class="empty-state">
        <text class="empty-text">暂无内容</text>
      </view>

      <view v-else class="list-items">
        <view v-for="item in contentList" :key="item.id" class="content-item">
          <view class="item-header">
            <text class="item-title" @click="doCopy(item.title)">{{ item.title }}</text>
            <text class="item-type">{{ item.type }}</text>
          </view>

          <!-- 文字内容 -->
          <TextDisplay v-if="item.type === 'text'" :texts="item.items" />

          <!-- 图片内容 -->
          <ImageDisplay v-if="item.type === 'image'" :images="item.items" />

          <!-- 链接内容 -->
          <LinkDisplay v-if="item.type === 'link'" :links="item.items" />

          <view class="item-footer">
            <view class="item-tags">
              <text v-for="tag in item.tags" :key="tag.id" class="tag-item">{{ tag.name }}</text>
            </view>
            <view class="item-actions">
              <button class="action-btn edit" @click="handleEdit(item)">编辑</button>
              <button class="action-btn delete" @click="handleDelete(item)">删除</button>
            </view>
          </view>
        </view>
      </view>

      <!-- 加载更多提示 -->
      <view v-if="!loading && hasMore" class="loading-more">
        <text>加载更多...</text>
      </view>
      <view v-if="!loading && !hasMore" class="no-more">
        <text>没有更多内容了</text>
      </view>
    </scroll-view>
  </Pages>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useContentStore } from '@/stores/content'
import CustomTabbar from '@/components/custom-tabbar.vue'
import TextDisplay from '@/components/content/TextDisplay.vue'
import ImageDisplay from '@/components/content/ImageDisplay.vue'
import LinkDisplay from '@/components/content/LinkDisplay.vue'

import Pages from '@/components/pages/index.vue'

const contentStore = useContentStore()
const selectedTypeIndex = ref(0)
const loading = ref(false)
const scrollHeight = ref(0)
const currentTab = ref(0)
const statusBarHeight = ref(0)  // 添加状态栏高度变量

// 内容列表
const contentList = computed(() => {
  return contentStore.contents
})

const doCopy = (text) => {
  uni.setClipboardData({
    data: text,
    success: () => {
      uni.showToast({
        title: '复制成功',
        icon: 'success'
      })
    }
  })
}

// 分页相关变量
const page = ref(1)
const pageSize = ref(10)
const hasMore = ref(true)
const refreshing = ref(false)

// 获取内容列表
// 添加下拉刷新处理方法
const handleRefresh = async () => {
  refreshing.value = true
  await fetchContentList(true)
}

// 切换标签
const onSys = () => {
  uni.navigateTo({
    url: '/pages/Sys/Sys'
  })
}


// 修改获取内容列表方法
const fetchContentList = async (isRefresh = false) => {
  if (isRefresh) {
    page.value = 1
    hasMore.value = true
  }

  if (!hasMore.value || (loading.value && !isRefresh)) return

  loading.value = true
  try {
    const type = contentStore.contentTypes[selectedTypeIndex.value]
    const result = await contentStore.fetchContents({
      type,
      page: page.value,
      pageSize: pageSize.value
    })

    // 修改这里的逻辑
    const newItems = result.items || []

    console.log('isRefresh', isRefresh)

    if (isRefresh) {
      contentStore.contents = newItems
    } else {
      // 使用 push 而不是直接赋值，避免引用问题
      newItems.forEach(item => {
        contentStore.contents.push(item)
      })
    }

    hasMore.value = newItems.length === pageSize.value
    if (hasMore.value) {
      page.value++
    }
  } catch (error) {
    uni.showToast({
      title: '加载失败',
      icon: 'none'
    })
  } finally {
    loading.value = false
    if (isRefresh) {
      refreshing.value = false
    }
  }
}

// 修改加载更多处理方法
const handleLoadMore = () => {
  if (!hasMore.value || loading.value) return
  fetchContentList(false)
}

// 类型切换
const handleTypeChange = async (e) => {
  selectedTypeIndex.value = e.detail.value
  await fetchContentList(true)
}

// 编辑内容
const handleEdit = (content) => {
  uni.navigateTo({
    url: `/pages/content/edit?id=${content.id}`
  })
}

// 删除内容
const handleDelete = (content) => {
  uni.showModal({
    title: '确认删除',
    content: '确定要删除该内容吗？',
    success: async (res) => {
      if (res.confirm) {
        try {
          await contentStore.deleteContent(content.id)
          uni.showToast({
            title: '删除成功',
            icon: 'success'
          })
          await fetchContentList(true) // 删除后刷新列表
        } catch (error) {
          uni.showToast({
            title: '删除失败',
            icon: 'none'
          })
        }
      }
    }
  })
}

// 初始化 scroll-view 高度
const initScrollHeight = () => {
  const systemInfo = uni.getSystemInfoSync()
  // #ifdef APP-PLUS
  statusBarHeight.value = systemInfo.statusBarHeight || 0
  scrollHeight.value = systemInfo.windowHeight - 120 - statusBarHeight.value
  // #endif

  // #ifndef APP-PLUS
  statusBarHeight.value = 20
  scrollHeight.value = systemInfo.windowHeight - 120
  // #endif
}

// 页面加载时初始化
onMounted(async () => {
  initScrollHeight()
  await fetchContentList(true)
})
</script>

<style lang="scss" scoped>
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 32rpx;
  background: #fff;
  padding: 24rpx;
  border-radius: 12rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);

  .header-title {
    font-size: 36rpx;
    font-weight: bold;
    color: #303133;
  }

  .header-actions {
    display: flex;
    gap: 16rpx;

    .type-picker {
      .picker-wrapper {
        background: #fff;
        border: 2rpx solid #dcdfe6;
        padding: 12rpx 24rpx;
        border-radius: 8rpx;

        .picker-text {
          color: #606266;
          font-size: 28rpx;
        }
      }
    }
  }
}

.content-list-container {

  .loading-state,
  .empty-state {
    background: #fff;
    border-radius: 12rpx;
    padding: 48rpx;
    text-align: center;
    color: #909399;
    font-size: 28rpx;
  }

  .list-items {
    .content-item {
      background: #fff;
      border-radius: 12rpx;
      padding: 24rpx;
      margin-bottom: 24rpx;
      box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);

      .item-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 16rpx;
        padding-bottom: 16rpx;
        border-bottom: 2rpx solid #f0f2f5;

        .item-title {
          font-size: 32rpx;
          font-weight: bold;
          color: #303133;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
          margin-right: 20rpx;
        }

        .item-type {
          font-size: 24rpx;
          color: #409eff;
          background: #ecf5ff;
          padding: 4rpx 16rpx;
          border-radius: 4rpx;
        }
      }

      .item-footer {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-top: 16rpx;
        padding-top: 16rpx;
        border-top: 2rpx solid #f0f2f5;

        .item-tags {
          display: flex;
          flex-wrap: wrap;
          gap: 8rpx;

          .tag-item {
            font-size: 24rpx;
            color: #67c23a;
            background: #f0f9eb;
            padding: 4rpx 12rpx;
            border-radius: 4rpx;
          }
        }

        .item-actions {
          display: flex;
          gap: 16rpx;

          .action-btn {
            font-size: 24rpx;
            padding: 8rpx 24rpx;
            border-radius: 4rpx;
            border: none;

            &.edit {
              color: #409eff;
              background: #ecf5ff;
            }

            &.delete {
              color: #f56c6c;
              background: #fef0f0;
            }
          }
        }
      }
    }
  }

  .loading-more,
  .no-more {
    text-align: center;
    padding: 20rpx;
    color: #909399;
    font-size: 24rpx;
  }
}


:deep(.uni-scroll-view-refresher) {
  background: none !important;
  margin-bottom: 20rpx;
}
</style>